package com.heima.schedule.service.imp;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.commons.CacheService;
import com.heima.common.commons.ScheduleConstants;
import com.heima.model.schedule.dto.Task;
import com.heima.model.schedule.pojo.Taskinfo;
import com.heima.model.schedule.pojo.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
@Transactional
public class TaskServiceImp implements TaskService {
    /**
     * 延迟添加任务
     * @param task   任务对象
     * @return
     */
    @Override
    public long addTask(Task task) {
        //添加任务到数据库当中
        Boolean success = savetodb(task);
        if (success) {
            //2.添加任务到redis
            addTaskToCache(task);
        }
        return task.getTaskId();
    }

    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;
//        删除数据库里的信息
        Task task = updateDb(taskId,ScheduleConstants.EXECUTED);
        if (task!=null){
            removeTaskFromCache(task);
            flag = true;
        }
        return flag;
    }


    /**
     * 按照类型和优先级拉取任务
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        Task task = null;
        try {
            String key = type+"_"+priority;
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if(StringUtils.isNotBlank(task_json)){
                task = JSON.parseObject(task_json, Task.class);
                //更新数据库信息
                updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return task;
    }

    /**
     * 删除redis中的数据
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType()+"_"+task.getPriority();
        if(task.getExecuteTime()<=System.currentTimeMillis()){
            cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));
        }else {
            cacheService.zRemove(ScheduleConstants.FUTURE+key, JSON.toJSONString(task));
        }
    }

    /**
     * 用于对数据库更新删除的方法
     * @param taskId
     * @param  status
     * @return
     */
    private Task updateDb(long taskId, int status) {
        Task task =null;
        try {
            taskinfoMapper.deleteById(taskId);
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return task;
    }

    /**
     * 添加任务到redis中
     * @param task
     */
    @Autowired
    private CacheService cacheService;
    private void addTaskToCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        long NEXTEXECUTETIME = calendar.getTimeInMillis();
        //2.1 如果任务的执行时间小于等于当前时间，存入list
            if (task.getExecuteTime()<=System.currentTimeMillis()){
                cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
            }else if (task.getExecuteTime()<=NEXTEXECUTETIME){
                //2.2 如果任务的执行时间大于当前时间 && 小于等于预设时间（未来5分钟） 存入zset中
                cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
            }

    }

    /**
     *  保存任务当数据库中
     * @param task
     * @return
     */
    @Autowired
    TaskinfoMapper taskinfoMapper;
    @Autowired
    TaskinfoLogsMapper taskinfoLogsMapper;
    private Boolean savetodb(Task task) {
        boolean flag = false;
        try {
            //保存任务表
            Taskinfo dbtaskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,dbtaskinfo);
            dbtaskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(dbtaskinfo);
            //将更新的id设置到task
            task.setTaskId(dbtaskinfo.getTaskId());
            //保存日志记录
            TaskinfoLogs dblogs = new TaskinfoLogs();
            BeanUtils.copyProperties(dbtaskinfo,dblogs);
            dblogs.setVersion(1);
            dblogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(dblogs);
            flag = true;
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 定时刷新future中的数据到list中
     */

    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh(){
        //利用redis分布式锁sexnx来解决一次刷新操作在在一个服务上
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if (StringUtils.isNotBlank(token)){
            //查询未来的所有数据
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {
                String topicKey =  ScheduleConstants.TOPIC+futureKey.split(ScheduleConstants.FUTURE)[1];
                //获取该组key下当前需要消费的任务数据
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                if (!tasks.isEmpty()) {
                    //将这些任务数据添加到消费者队列中
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    System.out.println("成功的将" + futureKey + "下的当前需要执行的任务数据刷新到" + topicKey + "下");
                }
            }
        }
    }

    /**
     * 5分钟刷定数据库的信息到redis中
     */
    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct
    public void reloadData(){
        //清理redis中的数据，避免重复
        clearCache();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        //查看小于未来5分钟的所有任务,有任务就添加
        List<Taskinfo> taskinfos =
                taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));
        if (taskinfos!=null){
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);
            }
        }
    }

    /**
     * 清理redis中的数据，避免重复
     */
    private void clearCache() {
        Set<String> futurekeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topickeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(futurekeys);
        cacheService.delete(topickeys);
    }

}
